import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useArticleListService, useGetArtDetailService } from '@/api/request.js'
import { baseURL } from '@/api/index.js'
// 文章模块
export const useArticleStore = defineStore(
  'useArticleStore',
  () => {
    // 文章列表
    const articleData = ref({
      data: [],
      total: 0
    })

    // 文章详情
    const article = ref({})
    // 获取位置列表
    const getArticleList = async (queryObj) => {
      const { data, total } = await useArticleListService(queryObj)
      console.log(data, total)
      // 处理后端时间数据格式问题
      articleData.value.data = data.map((e) => {
        if (e.pub_date) {
          e.pub_date = new Date(e.pub_date).toLocaleDateString()
        } else {
          e.pub_date = new Date().toLocaleDateString()
        }
        return e
      })
      articleData.value.total = total
    }

    // 获取文章详情
    const getArtDetail = async (id) => {
      const { data } = await useGetArtDetailService(id)
      console.log(data)
      article.value = data
      article.value.cover_img = baseURL + article.value.cover_img
    }

    return {
      articleData,
      article,
      getArticleList,
      getArtDetail
    }
  },
  {
    persist: true // 持久化
  }
)
